package com.eveinfo.display.asset;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;

public class SearchEditText extends EditText implements OnKeyListener {

	OnUsernameAvailableListener onUsernameAvailableListener = null;

	public SearchEditText(Context context) {
		super(context);
		// Set KeyListener to ourself
		this.setOnKeyListener(this);
	}

	public SearchEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// Set KeyListener to ourself
		this.setOnKeyListener(this);
	}

	public SearchEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		// Set KeyListener to ourself
		this.setOnKeyListener(this);
	}

	// Allows the user to set an Listener and react to the event
	public void setOnUsernameAvailableListener(OnUsernameAvailableListener listener) {
		onUsernameAvailableListener = listener;
	}

	// This function is called after the check was complete
	private void OnUserChecked(String username, boolean available) {
		// Check if the Listener was set, otherwise we'll get an Exception when
		// we try to call it
		if (onUsernameAvailableListener != null) {
			// Only trigger the event, when we have a username
			if (!TextUtils.isEmpty(username)) {
				onUsernameAvailableListener.onAvailableChecked(username, available);
			}
		}
	}

	@Override
	public boolean onKey(View v, int keycode, KeyEvent keyevent) {
		// We only want to handle ACTION_UP events, when user releases a key
		if (keyevent.getAction() == KeyEvent.ACTION_DOWN)
			return false;

		boolean available = true;

		// Whenever a user press a key, check if the username is available
		String username = getText().toString().toLowerCase();
		if (!TextUtils.isEmpty(username)) {
			
			// Trigger the Event and notify the user of our widget
			OnUserChecked(username, available);
			return false;
		}
		return false;
	}

	// Define our custom Listener interface
	public interface OnUsernameAvailableListener {
		public abstract void onAvailableChecked(String username, boolean available);
	}
}